package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.subform.TransferSubFormHelper;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.SupplierContactUserDao;
import com.xbongbong.saas.domain.entity.SupplierContactUserEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.enums.subform.PaymentSheetTeamEnum;
import com.xbongbong.saas.enums.subform.SupplierContactTeamEnum;
import com.xbongbong.saas.model.SupplierContactUserModel;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author haibin.zhang
 * @version v1.0
 * @date 2019/4/12 17:14
 * @since v1.0
 */
@Service("supplierContactUserModel")
public class SupplierContactUserModelImpl implements SupplierContactUserModel {
    @Resource
    private SupplierContactUserDao supplierContactUserDao;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private TransferSubFormHelper transferSubFormHelper;

    @Override
    public Integer save(SupplierContactUserEntity SupplierContactUserEntity) throws XbbException {
        if (SupplierContactUserEntity.getId() == null || SupplierContactUserEntity.getId().equals(0L)) {
            return insert(SupplierContactUserEntity);
        }
        return update(SupplierContactUserEntity);
    }

    @Override
    public SupplierContactUserEntity getByKey(Long key, String corpid) {
        return supplierContactUserDao.getByKey(key, corpid);
    }

    private Integer deleteBatch(List<Long> list, String corpid, Integer del) throws XbbException {
        return supplierContactUserDao.deleteBatch(list, corpid, del);

    }

    @Override
    public Integer insert(SupplierContactUserEntity entity) throws XbbException {
        long now = DateTimeUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);
        Integer result = supplierContactUserDao.insert(entity);

        PaasFormDataEntity paasFormDataEntity = transferSubFormHelper.transferUserTeamToFormData(IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM, entity);
        InsertDTO saveDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM);
        paasEsModel.insert(saveDTO);
//        paasEsModel.insert(entity,IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM,entity.getCorpid(),entity.getId(),entity.getDataId());
        return result;
    }

    @Override
    public Integer update(SupplierContactUserEntity entity) throws XbbException {
        long now = DateTimeUtil.getInt();
        entity.setUpdateTime(now);
        Integer result = supplierContactUserDao.update(entity);
        PaasFormDataEntity paasFormDataEntity = transferSubFormHelper.transferUserTeamToFormData(IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM, entity);
        InsertDTO saveDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM);
        paasEsModel.update(saveDTO);
//        paasEsModel.update(entity,IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM,entity.getCorpid(),entity.getId(),entity.getDataId());
        return result;
    }

    @Override
    public List<SupplierContactUserEntity> findEntitys(Map<String, Object> param) {
        return supplierContactUserDao.findEntitys(param);
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return supplierContactUserDao.getEntitysCount(param);
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return null;
    }

    @Override
    public void insetBatch(List<SupplierContactUserEntity> supplierContactUserEntityList) throws XbbException{
        insetBatch(supplierContactUserEntityList, WriteRequest.RefreshPolicy.NONE);
    }

    @Override
    public void insetBatch(List<SupplierContactUserEntity> supplierContactUserEntityList, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException{
        supplierContactUserDao.insertBatch(supplierContactUserEntityList);
        List<PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferUserTeamToFormDataList(IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM, supplierContactUserEntityList);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntities) {
            insertDTOList.add(paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM));
        }

        paasEsModel.insertBatch(insertDTOList, refreshPolicy);
    }

    @Override
    public List<UserTeamEntity> findBaseEntitys(Map<String, Object> map) {
        return supplierContactUserDao.findBaseEntitys(map);
    }

    @Override
    public void delete(SupplierContactUserEntity supplierContactUserEntity) throws XbbException {
        supplierContactUserEntity.setDel(1);
        supplierContactUserEntity.setUpdateTime((long) DateUtil.getInt());
        supplierContactUserDao.update(supplierContactUserEntity);
        paasEsModel.delete(supplierContactUserEntity.getId(), supplierContactUserEntity.getCorpid(), IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM,supplierContactUserEntity.getDataId());
    }

    @Override
    public void batchUpdateByUserIdIn(String corpid, List<Long> dataIdIn, List<UserTeamEntity> teamEntityList, Integer isMain, Integer del) throws XbbException {
        supplierContactUserDao.batchUpdateByIdIn(corpid, dataIdIn, isMain, del);
        List<InsertDTO> insertList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : teamEntityList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                map.put(SupplierContactTeamEnum.getAttrConnectData(SupplierContactTeamEnum.IS_MAIN), isMain);
            }
            if (Objects.nonNull(del)) {
                map.put(ParameterConstant.DEL, del);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList);
    }

    @Override
    public void batchUpdateByUserIdIn(String corpid, List<Long> dataIdIn, List<UserTeamEntity> teamEntityList, Integer isMain, Integer del, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        supplierContactUserDao.batchUpdateByIdIn(corpid, dataIdIn, isMain, del);
        List<InsertDTO> insertList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : teamEntityList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                map.put(SupplierContactTeamEnum.getAttrConnectData(SupplierContactTeamEnum.IS_MAIN), isMain);
            }
            if (Objects.nonNull(del)) {
                map.put(ParameterConstant.DEL, del);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, refreshPolicy);
    }

    @Override
    public List<SupplierContactUserEntity> getBySupplierId(String corpid, Long supplierId, Integer del) {
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put(StringConstant.CORPID, corpid);
        params.put("contactId", supplierId);
        params.put(StringConstant.DEL, del);
        return findEntitys(params);
    }

    @Override
    public List<SupplierContactUserEntity> getBySupplierId(String corpid, Long supplierId) {
        return supplierContactUserDao.getBySupplierId(corpid, supplierId);
    }

    @Override
    public void deleteBatchUser(List<SupplierContactUserEntity> delUserEntity, String corpid, Integer del) throws XbbException {
        if (CollectionUtils.isEmpty(delUserEntity)) {
            return;
        }
        List<Long> ids = new ArrayList<>();

        List<InsertDTO> insertDTOList = new ArrayList<>();
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
        map.put(StringConstant.DEL, del);
        for (SupplierContactUserEntity entity : delUserEntity){
            ids.add(entity.getId());
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM);
            insertDTO.setIndex(IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM.getIndex());
            insertDTO.setType(IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM.getType());
            insertDTO.setSource(map);
            insertDTOList.add(insertDTO);
        }
        deleteBatch(ids, corpid, del);
        paasEsModel.updateBatch(insertDTOList);
    }

    @Override
    public void updateBatch(List<SupplierContactUserEntity> supplierContactUserEntities, String corpid) throws XbbException {
        if (CollectionUtils.isEmpty(supplierContactUserEntities)) {
            return;
        }
        supplierContactUserDao.updateBatch(supplierContactUserEntities, corpid);

        List<PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferUserTeamToFormDataList(IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM, supplierContactUserEntities);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntities) {
            insertDTOList.add(paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM));
        }
        paasEsModel.updateBatch(insertDTOList);
    }

    @Override
    public void deleteByDataIds(List<Long> dataIds, String corpid) throws XbbException {
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("del",0);
        map.put("contactIdIn", dataIds);
        List<SupplierContactUserEntity> supplierContactUserEntities = findEntitys(map);
        supplierContactUserDao.deleteBatchByContactIdIn(dataIds, corpid);
        for (SupplierContactUserEntity entity : supplierContactUserEntities) {
            paasEsModel.delete(entity.getId(), corpid, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM, entity.getDataId());
        }
    }

    @Override
    public Integer deleteBatchBySupplierAndContact(Long supplierId, Long contactId, String corpid) throws XbbException {
        if (supplierId == null || corpid == null || contactId == null) {
            return 0;
        }
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("supplierId", supplierId);
        param.put("contactId", contactId);
        param.put("corpid", corpid);
        List<SupplierContactUserEntity> contactUserList = findEntitys(param);
        List<Long> list = new ArrayList<>();
        for (SupplierContactUserEntity contactUserEntity : contactUserList) {
            list.add(contactUserEntity.getId());
        }
        if (list.isEmpty()) {
            return 1;
        }
        Integer result = deleteBatch(list,corpid, DelEnum.DELETE.getDel());
        for (SupplierContactUserEntity entity :contactUserList){
            paasEsModel.delete(entity.getId(), corpid, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM,entity.getDataId());
//            entity.setDel(1);
//            entity.setUpdateTime(DateTimeUtil.getInt());
//            paasEsModel.update(entity,IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM,entity.getCorpid(),entity.getId(),entity.getContactId());
        }
        return result;
    }


    /**
     *
     * @Description: 编辑团队成员标签
     * @param supplierContactUserEntity
     * @return: void
     * @Author: shen.yang
     * @Date: 2022/1/17  14:20
     */
    @Override
    public void editLabel(SupplierContactUserEntity supplierContactUserEntity) throws XbbException {
        updateFormTeam(supplierContactUserEntity);
    }

    /**
     * 更新协同人可编辑权限
     *
     * @param supplierContactUserEntity
     */
    @Override
    public void updateEditFormPer(SupplierContactUserEntity supplierContactUserEntity) throws XbbException {
        updateFormTeam(supplierContactUserEntity);
    }


    private void updateFormTeam(SupplierContactUserEntity supplierContactUserEntity) throws XbbException {
        Long updateTime = DateTimeUtil.getInt();
        supplierContactUserEntity.setUpdateTime(updateTime);
        supplierContactUserDao.update(supplierContactUserEntity);
        InsertDTO insertDTO = new InsertDTO();
        String corpid = supplierContactUserEntity.getCorpid();
        insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM.getType() + "_" + corpid + "_" + supplierContactUserEntity.getId());
        insertDTO.setParent(corpid + "_" + supplierContactUserEntity.getDataId());
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("updateTime", updateTime);
        insertDTO.setSource(map);
        insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM);
        paasEsModel.update(insertDTO);
    }

    /**
     * 批量更新团队的人员为协同人身份以及协同人的可编辑权限
     *
     * @param corpid
     * @param idIn
     * @param teamEntityList
     * @param isMain
     * @param needThrow
     * @throws XbbException
     */
    @Override
    public void batchUpdateCoAndPerByUserIdIn(String corpid, List<Long> idIn, List<UserTeamEntity> teamEntityList, Integer isMain, boolean needThrow) throws XbbException {
        batchUpdateCoAndPerByUserIdIn(corpid, idIn, teamEntityList, isMain, needThrow, WriteRequest.RefreshPolicy.WAIT_UNTIL);
    }

    @Override
    public void batchUpdateCoAndPerByUserIdIn(String corpid, List<Long> idIn, List<UserTeamEntity> teamEntityList, Integer isMain, boolean needThrow, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        Integer formPermission = teamEntityList.get(BasicConstant.ZERO).getFormPermission();
        supplierContactUserDao.batchUpdateCoAndPerByUserIdIn(corpid, idIn, isMain, formPermission);
        List<InsertDTO> insertList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : teamEntityList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                JSONObject object = new JSONObject();
                object.put(PaymentSheetTeamEnum.IS_MAIN.getDataAttr(), isMain);
                map.put(StringConstant.JSON_DATA, object);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, refreshPolicy, needThrow);
    }

}
